package model

import (
	"fmt"
	"github.com/rs/zerolog/log"
	"shyxy-net/pkg/fiber"
	"time"
)

func (ms *Service) ListModels() ([]string, error) {
	var result fiber.Result
	var err error
	for i := 0; i < 3; i++ {
		err = ms.client.Get("/models", &result)
		if err == nil {
			break
		}
		log.Debug().Msgf("Attempt %d failed: %v", i+1, err)
		time.Sleep(100 * time.Millisecond)
	}
	if err != nil {
		return nil, err
	}

	if result.Code != 0 {
		return nil, fmt.Errorf("error msg:%s", result.Msg)
	}

	// 安全地获取 models 字段并转换为 []string
	modelsValue, exists := result.Data["models"]
	if !exists {
		return nil, fmt.Errorf("missing models in data")
	}

	// 处理不同的数组类型
	var models []string
	switch v := modelsValue.(type) {
	case []interface{}:
		models = make([]string, len(v))
		for i, item := range v {
			models[i] = fmt.Sprintf("%v", item) // 转换为字符串
		}
	case []string:
		models = v
	default:
		return nil, fmt.Errorf("unexpected models type: %T", v)
	}

	return models, nil
}
